<?php
$config = require 'config.php';
// 接收并验证数据
$nick  = trim($_POST['nickname'] ?? '');
$pass  = $_POST['password'] ?? '';
$email = trim($_POST['email'] ?? '');
if (!$nick || !$pass || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    exit('输入不合法');
}

// 连接数据库
$dsn = "mysql:host={$config['db']['host']};dbname={$config['db']['dbname']};charset={$config['db']['charset']}";
$pdo = new PDO($dsn, $config['db']['user'], $config['db']['pass'], [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

// 检查昵称是否存在或过期释放
$stmt = $pdo->prepare("SELECT id, created_at, activated_at FROM users WHERE nickname = ?");
$stmt->execute([$nick]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
    if (!$user['activated_at'] && (time() - strtotime($user['created_at']) > 3600)) {
        // 超时未激活，删除旧记录
        $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$user['id']]);
    } else {
        exit('昵称已被占用');
    }
}

// 插入新用户（未激活）
$createdAt = date('Y-m-d H:i:s');
// 生成验证码（用户名哈希）
$code = substr(hash('sha256', $nick . $createdAt), 0, 16);
$passHash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $pdo->prepare(
    "INSERT INTO users (nickname, password_hash, email, verify_code, created_at)
     VALUES (?, ?, ?, ?, ?)"
);
$stmt->execute([$nick, $passHash, $email, $code, $createdAt]);

// 发送激活邮件
auto_mail:
$verifyLink = $config['mail']['base_url']
    . '?user=' . urlencode($nick)
    . '&code=' . $code;
$message = "请点击以下链接激活账号：\n" . $verifyLink;
mail(
    $email,
    $config['mail']['subject'],
    $message,
    "From: {$config['mail']['from']}"
);
echo '注册成功，请查收激活邮件';
?>